# -* - coding: UTF-8 -* -
#import sys 
#reload(sys)
#sys.setdefaultencoding('utf8')

import socket,socketserver,time,json
import threading
from time import sleep
import logging
from websocket_server import WebsocketServer

#提交任务到FastCGI
#UDP监听线程
class Socket(object):  
	def __init__(self, coop,cmd_factory):  
		self.coop = coop
		self.cmd_factory = cmd_factory
		self.is_sigint_up=True
	def start(self):
		logging.info("Socket.Start")
		self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
		#绑定同一个域名下的所有机器
		self.sock.bind(('', 9981))
		#self.sock.settimeout(1)
		while self.is_sigint_up:
			try:
				self.sock.settimeout(1)
				request, addr = self.sock.recvfrom(2048)
			except socket.timeout:
				self.sock.settimeout(None)
				#logging.info('timeout:')
				continue
			except Exception as e:
				logging.error('Socket.start')
				logging.exception(e)
			#except
			if not request:  
				#print("请求为空")
				continue
			logging.info("received"+str(addr)+":"+str(request))	 # 接收客户端的ip, port
			req_str=request.decode('utf8')
			if req_str.startswith("{") and req_str.endswith("}"):
				try:
					#logging.info('收到命令:',req_str)
					task= json.loads(req_str)
					if task['mode'] and task['command']:
						self.cmd_factory.add(task['mode'],task['command'],task['data'])
					#self.queue.join()
					#print(data['test'])
				except Exception as e:
					logging.error('执行出错:',e)
			elif req_str.startswith('create '):
				cmd = req_str.split(' ')
				logging.info('收到创建服务器！'+cmd[1])
				self.coop.create_server(cmd[1])
				logging.info('成功创建本机服务队列')
			elif req_str=='quit':
				logging.info('收到退出命令，开始退出！')
				logging.info(str(self.coop))
				self.coop.terminate()
				logging.info('退出成功！')
				break
			elif req_str=='stop_manage':
				logging.info('收到停止管理命令，开始停止！')
				self.coop.manage_center.stop()
				self.coop.manage_center.terminate()
				logging.info('停止管理成功！')
			elif req_str=='start_manage':
				logging.info('收到启动管理命令，开始启动！')
				logging.info(str(self.coop))
				self.coop.manage_center.start()
				logging.info('启动管理成功！')				
			elif req_str=='restart':
				logging.info('收到重启命令，开始退出！')
				logging.info(str(self.coop))
				self.coop.stop()
				logging.info('重启成功！')
				self.coop.start()
				logging.info('启动成功！')
				break				
		self.sock.close()
	def stop(self):
		self.is_sigint_up=False
		
class Server(object):  
	clients={}
	def __init__(self,coop):
		self.websoket = False
		self.coop = coop
		
	def on_message(self,client, server,message):
		logging.info("收到消息{}".format(message))
		cmd=message.split(' ')
		if cmd[0]:
			if cmd[0]=='login' and cmd[1]:
				client.set_name(cmd[1])
			elif (cmd[0]=='incoming' or cmd[0]=='idle' or cmd[0]=='offhook') and cmd[1] and client.name:
				self.sendTo(client.name[0],message)

	def start(self):
		if not self.websoket:
			self.websoket = WebsocketServer(host='0.0.0.0', port=9981)
			self.websoket.set_fn_message_received(self.on_message)
			#self.websocket_thread=threading.Thread(target=self.websoket.run_forever,name="web_socket",daemon=True)
		
		self.websoket.run_forever(True)
		
	def stop(self):
		if self.websoket:
			self.websoket.shutdown_gracefully() #告诉serve_forever循环停止。
		
	def sendTo(self,user,msg):
		logging.info("sendTo:{},{}".format(user,msg))
		self.websoket.send_message_by_name(user,msg)
				
	def sendAll(self,msg):
		self.websoket.send_message_to_all(msg)	

def test():
	logging.basicConfig(level=logging.DEBUG, filemode = 'a')
	server = Server({})
	server.start()
	while True:
		cmd = input(">>>")
		if cmd.strip() == "quit":
			server.stop() #告诉serve_forever循环停止。
			break
		else:
			server.sendTo('18602726253',1111)
#test()
